package jude.java.money.batch;

import static jude.java.money.batch.Definition.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class Log {
	
	public static final int LEVEL_SUCCESS = 1;
	public static final int LEVEL_ALL = Integer.MAX_VALUE;

	private static final String[] IGNORES = {
		SUCCESS,
	};
	private static final String[] IGNORE_PREFIX = {
		IGNORE,
	};
	
	private StringBuilder cache = new StringBuilder();
	private boolean filter = true;
	private boolean allIgnored = true;
	private Writer writer;
	private String id;
	private boolean skip = false;
	
	public Log() {
	}
	
	public Log(String fileName) {
		try {
			this.writer = new FileWriter(fileName, true);
		} catch (IOException e) {
		}
	}
	
	public void out(Object... msgs) {
		try {
			for (int i = 0; i < msgs.length; i++) {
				if (writer != null)
					writer.write(String.valueOf(msgs[i]));
				System.out.print(msgs[i]);
			}
		} catch (IOException e) {
			System.err.print(msgs[0]);
		}
	}
	
	public Log start(String msg) {
		id = null;
		if (!filter) {
			out(msg);
			return this;
		}
		allIgnored = true;
		if (cache.length() > 0) {
			out(msg);
			cache.setLength(0);
		}
		cache.append(msg);
		return this;
	}
	
	public Log id(String msg) {
		this.id = msg;
		log(msg);
		return this;
	}
	
	public Log end() {
		if (!filter)
			return this;
		if (!allIgnored) {
			out(cache);
		} else if (id != null) {
			if (skip) {
//				System.out.println(id + "\tskipped");
			} else {
				System.out.println(id);
			}
		}
		cache.setLength(0);
		if (writer != null)
			try {
				writer.flush();
			} catch (IOException e) {
			}
		return this;
	}
	
	public Log terminate() {
		if (writer != null) {
			try {
				writer.flush();
			} catch (IOException e) {
			}
			writer = null;
		}
		return this;
	}
	
	public Log result(String msg) {
		return result(-1, msg);
	}
	
	public Log result(int index, String msg) {
		String s = index>=0 ? (index+1) + "\t" : "";
		if (!filter || msg == null) {
			out("\r\n", s, msg);
			return this;
		}
		for (int i = 0; i < IGNORES.length; i++) {
			if (IGNORES[i].equals(msg))
				return this;
		}
		for (int i = 0; i < IGNORE_PREFIX.length; i++) {
			if (msg.startsWith(IGNORE_PREFIX[i]))
				return this;
		}
		allIgnored = false;
		cache.append("\r\n").append(s).append(msg);
		return this;
	}
	
	public Log skip(boolean skip) {
		this.skip = skip;
		return this;
	}
	
	public Log log(Object msg) {
		if (!filter || msg == null) {
			out(msg);
			return this;
		}
		cache.append(msg);
		return this;
	}
}
